using B.S.Data.MES.API.Applications.CangKu.Command;
using B.S.Data.MES.API.Dto.CangKuDTO;
using B.S.Domain.CangKu;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.Data.MES.API.Applications.CangKu.CommandHandlers
{
    /// <summary>
    /// 处理储位与仓库区域关联查询命令
    /// </summary>
    public class GetChuWeiWithCangKuQUCommandHandler : IRequestHandler<GetChuWeiWithCangKuQUCommand, APIRequst<APIPageing<List<ChuWeiWithCangKuQUDTO>>>>
    {
        private readonly IBaseRepository<ChuWei> _chuWeiRepository;
        private readonly IBaseRepository<CangKuQU> _cangKuQuRepository;
        
        /// <summary>
        /// 构造函数，注入仓储
        /// </summary>
        /// <param name="chuWeiRepository">储位仓储</param>
        /// <param name="cangKuQuRepository">仓库区域仓储</param>
        public GetChuWeiWithCangKuQUCommandHandler(IBaseRepository<ChuWei> chuWeiRepository, IBaseRepository<CangKuQU> cangKuQuRepository)
        {
            _chuWeiRepository = chuWeiRepository;
            _cangKuQuRepository = cangKuQuRepository;
        }
       
        public Task<APIRequst<APIPageing<List<ChuWeiWithCangKuQUDTO>>>> Handle(GetChuWeiWithCangKuQUCommand request, CancellationToken cancellationToken)
        {
            var query = from cw in _chuWeiRepository.GetAll()
                        join ck in _cangKuQuRepository.GetAll()on cw.KuWeiId equals ck.CangKuId
                        select new ChuWeiWithCangKuQUDTO
                        {
                            ChuId = cw.ChuId,
                            ChuNo = cw.ChuNo,
                            ChuName = cw.ChuName,
                            KuWeiId=cw.KuWeiId,
                            CangKuName = ck.CangKuName,
                            BM = ck.BM,
                            MShu = cw.MShu,
                            CreateName = cw.CreateName,
                            CreateTime = cw.CreateTime,
                            UpdateTime = cw.UpdateTime
                        };

            APIPageing<List<ChuWeiWithCangKuQUDTO>> Page = new APIPageing<List<ChuWeiWithCangKuQUDTO>>();
            Page.TotalCount=query.Count();
            Page.Total = (int)Math.Ceiling((1.0 * Page.TotalCount) / request.PageSize);
            Page.Data = query.OrderBy(x => x.ChuId).Skip((request.Pageindex - 1) * request.PageSize).Take(request.PageSize).ToList();

            return Task.FromResult(new APIRequst<APIPageing<List<ChuWeiWithCangKuQUDTO>>>
            {
                Code = RequstCode.成功,
                Msg = RequstCode.成功.ToString(),
                Data = Page
            });
        }
    }
}